/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.util;

import java.util.Properties;

public class Configuration extends Properties {

  private static final long serialVersionUID = 1L;
  
  public Configuration(Properties p) {
    super();
    this.putAll(p);
  }

  public Configuration(String propertyFileName) {
    super();
    Properties p = PropertiesUtil.loadProperties(propertyFileName);
    this.putAll(p);
  }
  
  public Configuration(String[] args) {
    super();
    override(args);
  }
  
  public void override(String[] args) {
    for (String arg : args) {
      String[] elements = arg.split("[ ]*=[ ]*");
      if (elements.length != 2) {
        this.put(arg.replaceFirst("\\-*", ""), "");
        continue;
      }
      String key = elements[0].replaceFirst("\\-*", "");
      String value = elements[1];
      this.put(key, value);
    }
  }
  
  /* (non-Javadoc)
   * @see java.util.Properties#getProperty(java.lang.String)
   */
  @Override
  public String getProperty(String key) {
    String value = super.getProperty(key);
    if ( value!=null ) {
      value = value.trim();
    }
    return value;
  }

  protected <T extends Enum<T>> T read(Class<T> c, Properties p, String key)
          throws ConfigurationException {
    T enumType = null;
    try {
      enumType = Enum.valueOf(c, (String) p.get(key));
    } catch (NullPointerException e1) {
      throw new ConfigurationException("required parameter " + key + " is not set");
    } catch (IllegalArgumentException e2) {
      throw new ConfigurationException(key + " configuration is invalid");
    }
    return enumType;
  }

  public String readString(Properties p, String key) throws ConfigurationException {
    String value = null;
    try {
      value = (String) p.get(key);
    } catch (NullPointerException e1) {
      throw new ConfigurationException("required parameter " + key + " is not set");
    }
    return value;
  }

  public static class ConfigurationException extends Exception {

    private static final long serialVersionUID = 1L;

    public ConfigurationException(String string) {
      super(string);
    }
  }

}
